<template>
  <div
    class="w100"
    :class="classList"
  >
    <span class="tip-icon-inner"></span>
    <el-input-number
      v-bind="{ ...item }"
      @change="handleInputChange"
      v-if="item && item.config?.dataType && ['integer', 'float', 'number'].includes(item.config.dataType.type)"
      v-model.number="changeValue"
    />
    <el-input
      v-bind="{ ...item }"
      v-else
      type="text"
      v-model="changeValue"
      @change="handleInputChange"
    >
      <template
        v-if="item && item.prepend"
        #prefix
      >
        {{ item?.prepend }}
      </template>
      <template
        v-if="item && item.append"
        #suffix
      >
        {{ item?.append }}
      </template>
    </el-input>
  </div>
</template>

<script setup lang="ts" name="TInput">
import { onMounted, watch } from "vue";
import { useFormItemExam } from "@/views/formgen/components/FormItem/hooks/useExamHook";
import { formEmits, formItemProps, useFormItem } from "@/views/formgen/components/FormItem/hooks/useFormItemHook";
import { BasicComponent } from "@/views/formgen/components/GenerateForm/types/form";
import { postRequest } from "@/api/baseRequest";
import { inject } from "vue-demi";
import { ReturnTypeOfUseUserForm } from "@/views/formgen/components/GenerateForm/hooks/useUserForm";
import { USER_FORM_STATE_KEY } from "@/views/formgen/components/GenerateForm/types/constants";

const props = defineProps({
  ...formItemProps
});

const emits = defineEmits(formEmits);

const examHook = useFormItemExam(<BasicComponent>props.item);

const { classList } = examHook;

const { changeValue, updateValue } = useFormItem(props, emits, false);
const userFormStore = inject<ReturnTypeOfUseUserForm>(USER_FORM_STATE_KEY);

const handleInputChange = (val: any) => {
  classList.value = examHook.getExamClass(changeValue.value, null);
  // 数据关联
  handleLinkData();
  updateValue(val);
};

// 检查开启了显示答案没
watch(
  () => props.item?.examConfig?.showAnswer,
  () => {
    classList.value = examHook.getExamClass(changeValue.value, null);
  }
);

const handleLinkData = () => {
  if (!props.item?.config?.dataLinkConfig || !changeValue.value) {
    return;
  }
  postRequest("/form/ext/getLinkDataResult", {
    inputValue: changeValue.value,
    dataLinkConfig: props.item?.config?.dataLinkConfig
  }).then(res => {
    if (res.data) {
      Object.keys(res.data).forEach(key => {
        userFormStore!.setFormModelItem(key, res.data[key]);
      });
    }
  });
};

onMounted(() => {
  handleInputChange(changeValue);
});
</script>
<style scoped lang="scss">
@use "../../../assets/styles/exam" as *;
</style>
